package redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;

import java.util.concurrent.TimeUnit;

/**
 * @author tbc on 2016/12/7 17:01:58.
 */
public class RedisSample {
    private static Jedis jedis = RedisHelper.getClientFromPool();


    public static void main(String[] args) {
        publish();

    }

    /**
     * 定时任务，维持心跳
     */
    private static void pingPong() {
        int failCount = 0;
        while (true) {
            if (failCount >= 3) {
                //TODO... 重新连接？
                jedis.close();
                jedis = RedisHelper.getClientFromPool();
            }
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                throw new RuntimeException(e.getMessage(), e);
            }

            if ("PONG".equals(jedis.ping())) {
                failCount = 0;
                continue;
            }

            failCount++;
        }
    }

    public static void publish() {
        String serviceAddress = "192.168.1.189:8080";
        String serviceName = "testService";
        String registryPath = "rubbish:registry:";
        String node = registryPath + serviceName;

        jedis.select(9);

        jedis.sadd(node, serviceAddress);
        jedis.publish(serviceName, node);
    }

    public static void subscribe() {
        jedis.select(9);
        final MyListener listener = new MyListener();
        //可以订阅多个频道
        //订阅得到信息在lister的onMessage(...)方法中进行处理
        //jedis.subscribe(listener, "foo", "watson");

        //也用数组的方式设置多个频道
        //jedis.subscribe(listener, new String[]{"hello_foo","hello_test"});

        //这里启动了订阅监听，线程将在这里被阻塞
        //订阅得到信息在lister的onPMessage(...)方法中进行处理
        jedis.psubscribe(listener, "rubbish:registry:");//使用模式匹配的方式设置频道
    }


    static class MyListener extends JedisPubSub {
        // 取得订阅的消息后的处理
        public void onMessage(String channel, String message) {
            System.out.println(channel + "=" + message);
        }

        // 初始化订阅时候的处理
        public void onSubscribe(String channel, int subscribedChannels) {
            // System.out.println(channel + "=" + subscribedChannels);
        }

        // 取消订阅时候的处理
        public void onUnsubscribe(String channel, int subscribedChannels) {
            // System.out.println(channel + "=" + subscribedChannels);
        }

        // 初始化按表达式的方式订阅时候的处理
        public void onPSubscribe(String pattern, int subscribedChannels) {
            // System.out.println(pattern + "=" + subscribedChannels);
        }

        // 取消按表达式的方式订阅时候的处理
        public void onPUnsubscribe(String pattern, int subscribedChannels) {
            // System.out.println(pattern + "=" + subscribedChannels);
        }

        // 取得按表达式的方式订阅的消息后的处理
        public void onPMessage(String pattern, String channel, String message) {
            System.out.println(pattern + "=" + channel + "=" + message);
        }
    }

}
